//
//  QLMAddBaoxiuVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/14.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMAddBaoxiuVC.h"
#import "QLMAddBaoxiuTopCell.h"
#import "QLMAddBaoxiuBotCell.h"
#import "QLMAddressBookModel.h"
#import <CTAssetsPickerController.h>
#import "QLMPhotoInfoTabCell.h"

#import "QLMDeviceListVC.h"
#import "QLMEditLocationVC.h"

#import "QLMBaoyangDeviceTabCell.h"
#import "QLMAvilabAddrInfoView.h"
#import "AppDelegate.h"

#import "QLMBXOrderDetailVC.h"
#import "QLMOrderListArrModel.h"

@interface QLMAddBaoxiuVC ()<UITableViewDataSource,UITableViewDelegate,QLMAddBaoxiuTopCellDelegate,QLMAddBaoxiuBotCellDelegate,CNContactPickerDelegate,UITextViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CTAssetsPickerControllerDelegate,QLMPhotoInfoTabCellDelegate,QLMBaoyangDeviceTabCellDelegate,UITextFieldDelegate,ABPeoplePickerNavigationControllerDelegate>{
    
    QLMAddBaoxiuBotCell *bottomcell;
    QLMAddBaoxiuTopCell *topcell;
    QLMPhotoInfoTabCell *photocell;
    QLMBaoyangDeviceTabCell *topBaoyangcell;
    
    NSString *classificationId;
    NSString *textViewText;
    UIButton *sureButton;
    
    UITableView *_addtableview;
    
    NSString *typeBxStr;
}

@property (nonatomic,strong) NSMutableArray *itemArray;
@property (nonatomic,strong) NSDictionary *brandDic;
@property (nonatomic,strong) NSMutableArray *btnArray;
@property (nonatomic,strong) NSMutableDictionary *addressDic;
@property (nonatomic,strong) NSMutableDictionary *deviceDic;
@property (nonatomic,strong) NSMutableArray *selectedPhotos;
@property (nonatomic,strong) NSMutableArray *selectUrlArr;

@end

@implementation QLMAddBaoxiuVC

- (BOOL)isNull:(id)object{
    // 判断是否为空串
    if ([object isEqual:[NSNull null]]) {
        return NO;
    }else if ([object isKindOfClass:[NSNull class]]){
        return NO;
    }else if (object==nil){
        return NO;
    }else if ([object isEqualToString:@"(null)(null)(null)(null)(null)"]){
        return NO;
    }
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (_isBaoyangDevicebool) {
        self.title=@"保养订单";
    }else{
        self.title=@"报修订单";
    }
    _addressDic=[NSMutableDictionary dictionary];
    
    NSString *addStr=[[NSUserDefaults standardUserDefaults] objectForKey:kDefaultAddress];
    if (![self isNull:addStr]) {
        
        NSDictionary *tmplocDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"enddic"];
        NSString *addreDetalStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"detailAddr"];
        if ([self isNull:addreDetalStr]) {
            [_addressDic setObject:addreDetalStr forKey:@"repairAddress"];
            [_addressDic setObject:tmplocDic[@"longtitu"] forKey:@"repairLongitude"];
            [_addressDic setObject:tmplocDic[@"latitu"] forKey:@"repairLatitude"];
        }
        
    }else{
        
        NSDictionary *tmplocDic = [[NSUserDefaults standardUserDefaults] objectForKey:kDefaultEnddic];
        if ([tmplocDic allKeys].count!=0) {
            [_addressDic setObject:addStr forKey:@"repairAddress"];
            [_addressDic setObject:tmplocDic[@"longtitu"] forKey:@"repairLongitude"];
            [_addressDic setObject:tmplocDic[@"latitu"] forKey:@"repairLatitude"];
        }
        
    }
    
    _deviceDic=[NSMutableDictionary dictionary];
    _selectUrlArr=[NSMutableArray array];
    _selectedPhotos=[NSMutableArray array];
    _itemArray=[NSMutableArray array];
    _brandDic=[NSDictionary dictionary];
    _btnArray=[NSMutableArray array];
    
    UIView *topBackView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 30)];
    topBackView.backgroundColor=UIColorFromRGB(0xcfab1c);
    [self.view addSubview:topBackView];
    
    UIButton *addreTipButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addreTipButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
    addreTipButton.frame = CGRectMake(kScreen_width-70-5, 0, 70, 30);
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"可用地区"];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    [addreTipButton setAttributedTitle:str forState:UIControlStateNormal];
    [str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x007eff) range:NSMakeRange(0,4)];
    
    addreTipButton.titleLabel.font=[UIFont systemFontOfSize:15.0f];
    addreTipButton.backgroundColor=[UIColor clearColor];
    [addreTipButton addTarget:self action:@selector(avilabeladdressInfo) forControlEvents:UIControlEventTouchUpInside];
    [topBackView addSubview:addreTipButton];

    UIImageView *noticeImageView=[[UIImageView alloc] initWithFrame:CGRectMake(10, 7.5, 18, 15)];
    noticeImageView.image=[UIImage imageNamed:@"tongzhi"];
    [topBackView addSubview:noticeImageView];
    
    UILabel *addreTipLabel=[[UILabel alloc] initWithFrame:CGRectMake(30, 0, kScreen_width-75-30, 30)];
    addreTipLabel.font=[UIFont systemFontOfSize:15];
    addreTipLabel.textColor=UIColorFromRGB(0x695200);
    addreTipLabel.text=@"目前维修服务仅对部分地区使用";
    addreTipLabel.textAlignment=NSTextAlignmentLeft;
    [topBackView addSubview:addreTipLabel];
    
    CGRect tabFrame=CGRectMake(0, topBackView.frame.origin.y+35, kScreen_width, kScreen_height-35-40-QLM_StatusBarAndNavigationBarHeight);
    _addtableview=[[UITableView alloc] initWithFrame:tabFrame style:UITableViewStylePlain];
    _addtableview.backgroundColor=[UIColor clearColor];
    _addtableview.delegate=self;
    _addtableview.dataSource=self;
    _addtableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    _addtableview.showsVerticalScrollIndicator=NO;
    _addtableview.showsHorizontalScrollIndicator=NO;
    _addtableview.tableFooterView=[UIView new];
    _addtableview.tableHeaderView=[UIView new];
    [self.view addSubview:_addtableview];
    
    sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sureButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
    sureButton.frame = CGRectMake(0, kScreen_height-40-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight, kScreen_width, 40);
    [sureButton setTitle:@"提交" forState:UIControlStateNormal];
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureButton.backgroundColor=kButtonColor;
    sureButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
    [sureButton addTarget:self action:@selector(_addBxOrderAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureButton];
    
    if (@available(iOS 11.0, *)) {
        _addtableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)avilabeladdressInfo{
    NSString *message=@"小马快修目前可用地区：湖北、重庆、四川、新疆、广西、山西";
    NSString *title = @"提示";
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    //改变title的大小和颜色
    NSMutableAttributedString *titleAtt = [[NSMutableAttributedString alloc] initWithString:title];
    [titleAtt addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:18] range:NSMakeRange(0, title.length)];
    [titleAtt addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, title.length)];
    [alertController setValue:titleAtt forKey:@"attributedTitle"];
    //改变message的大小和颜色
    NSMutableAttributedString *messageAtt = [[NSMutableAttributedString alloc] initWithString:message];
    [messageAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, message.length)];
    [messageAtt addAttribute:NSForegroundColorAttributeName value:[UIColor darkTextColor] range:NSMakeRange(0, message.length)];
    [alertController setValue:messageAtt forKey:@"attributedMessage"];
    
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"知道了",nil) style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:alertAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - QLMAddBaoxiuTopCellDelegate
- (void)_addDeviceAction{
//    __weak QLMAddBaoxiuVC *weakself=self;
    QLMDeviceListVC *deviceListVC=[QLMDeviceListVC new];
    deviceListVC.block = ^(NSString *equipmentId, NSString *modelId, NSString *machineId,NSString *deviceNameStr) {
        
        [self.deviceDic setObject:equipmentId forKey:@"equipmentId"];
        [self.deviceDic setObject:modelId forKey:@"modelId"];
        
        if (self.isBaoyangDevicebool) {
            topBaoyangcell.devicenameTF.text=deviceNameStr;
        }else{
            topcell.devicenameTF.text=deviceNameStr;
        }
    };
    deviceListVC.isCannotEdit=YES;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:deviceListVC animated:YES];
}

- (void)addBaoyangDeviceAction{
    [self _addDeviceAction];
}

- (void)addDeviceAction{
    [self _addDeviceAction];
}

- (void)troubleTypeAction:(NSInteger)btnTag{

    if (btnTag>879) {
        classificationId=[NSString stringWithFormat:@"%ld",btnTag-880];
        for (UIButton *tmpbtn in _btnArray) {
            if (tmpbtn.tag==btnTag) {
                tmpbtn.backgroundColor=UIColorFromRGB(0xf5c61b);
                [tmpbtn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
            }else{
                tmpbtn.backgroundColor=UIColorFromRGB(0xf6f6f6);
                [tmpbtn setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
            }
        }
    }else{
        if (btnTag==878) {
            typeBxStr=@"1";
            classificationId=nil;
            for (UIButton *tmpbtn in _btnArray) {
                tmpbtn.hidden=NO;
                tmpbtn.backgroundColor=UIColorFromRGB(0xf6f6f6);
                [tmpbtn setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
            }
            
            topcell.baoxiuBtn.backgroundColor=UIColorFromRGB(0xf5c61b);
            [topcell.baoxiuBtn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
            
            topcell.baoyangBtn.backgroundColor=UIColorFromRGB(0xf6f6f6);
            [topcell.baoyangBtn setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
            
            topcell.troubleLabel.hidden=NO;
        }else{
            typeBxStr=@"2";
            classificationId=@"4";
            for (UIButton *tmpbtn in _btnArray) {
                tmpbtn.hidden=YES;
            }
            
            topcell.baoyangBtn.backgroundColor=UIColorFromRGB(0xf5c61b);
            [topcell.baoyangBtn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
            
            topcell.baoxiuBtn.backgroundColor=UIColorFromRGB(0xf6f6f6);
            [topcell.baoxiuBtn setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
            
            topcell.troubleLabel.hidden=YES;
        }
        
        [_addtableview beginUpdates];
        [_addtableview endUpdates];
    }
}

- (void)_addBxOrderAction{
    
    [self.view endEditing:YES];
    
    if ([_deviceDic allKeys].count==0) {
        ETToast(@"请选择设备");
        return;
    }
    
    if (typeBxStr.length==0) {
        ETToast(@"请选择服务类型");
        return;
    }
    
    textViewText=@"";
    if (_isBaoyangDevicebool) {
        textViewText=topBaoyangcell.trodecriptionTextView.text;
    }else{
        if (classificationId.length==0) {
            ETToast(@"请选择故障选择类型");
            return;
        }
        textViewText=topcell.trodecriptionTextView.text;
    }
    
    if (bottomcell.truthNameTextField.text.length==0) {
        ETToast(@"请填写联系人姓名");
        return;
    }
    if (bottomcell.phoneNumTextField.text.length==0) {
        ETToast(@"请填写联系电话");
        return;
    }
    if (![ClientTool isMobileValid:bottomcell.phoneNumTextField.text]) {
        ETToast(@"请输入正确的手机号码");
        return;
    }
    
    if (textViewText.length==0){
        textViewText=@"";
        ETToast(@"请填写故障说明");
        return;
    }
    
    if ([self stringContainsEmoji:textViewText]) {
        ETToast(@"故障说明不能输入表情");
        return;
    }
    
    if ([_addressDic allKeys].count==0) {
        ETToast(@"请选择地址");
        return;
    }
    
    [self addBaoxiuAlert];
}

- (void)commitClick{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:_deviceDic[@"equipmentId"] forKey:@"equipmentId"];
    [dic setObject:_deviceDic[@"modelId"] forKey:@"modelId"];
    [dic setObject:bottomcell.truthNameTextField.text forKey:@"contactName"];
    [dic setObject:bottomcell.phoneNumTextField.text forKey:@"contactPhone"];
    [dic setObject:textViewText forKey:@"statusStatement"];
    
    if (!_isBaoyangDevicebool) {
        if (classificationId.length==0) {
            ETToast(@"请选择故障类型");
            return;
        }
        [dic setObject:classificationId forKey:@"classificationId"];
    }else{
        [dic setObject:@"4" forKey:@"classificationId"];
    }
    
    [dic setObject:_addressDic[@"repairAddress"] forKey:@"repairAddress"];
    [dic setObject:_addressDic[@"repairLongitude"] forKey:@"repairLongitude"];
    [dic setObject:_addressDic[@"repairLatitude"] forKey:@"repairLatitude"];
    sureButton.enabled=NO;
    NSMutableArray *picArray=[NSMutableArray array];
    for (NSString *urlStr in _selectUrlArr) {
        NSString *actualUrlStr=[NSString stringWithFormat:@"%@",urlStr];
        NSDictionary *imageUrlDic=[NSDictionary dictionaryWithObjectsAndKeys:actualUrlStr,@"pathName", nil];
        [picArray addObject:imageUrlDic];
    }
    
    [dic setObject:picArray forKey:@"pictureDetail"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/test/repairOrder/add" withParamers:dic andBody:tokenDic
                    success:^(id responseObject){
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            [self requRepairOrder:responseObject[@"orderId"]];
                        }else{
                            [self.view hideToastActivity];
                            ETToast(responseObject[@"msg"]);
                        }
                        sureButton.enabled=YES;
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                        sureButton.enabled=YES;
                    }
     ];
}

- (void)requRepairOrder:(NSString *)repairOrderId{
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:repairOrderId forKey:@"repairOrderId"];
    [ClientTool postUrlPath:@"/test/repairOrder/orderInfo" withParamers:paramerDic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            QLMOrderListInfoModel *resultInfoModel=[[QLMOrderListInfoModel alloc] initWithDictionary:responseObject[@"repairOrder"] error:nil];
                            
                            AppDelegate *appdel=(AppDelegate *)[UIApplication sharedApplication].delegate;
                            appdel.tabbarController.selectedIndex=1;
                            
                            QLMBXOrderDetailVC *detailVC=[QLMBXOrderDetailVC new];
                            detailVC.repairOrderId=repairOrderId;
                            detailVC.resultInfoModel=resultInfoModel;
                            detailVC.isBXAddJumpBool=YES;
                            
                            appdel.secondViewCtr.hidesBottomBarWhenPushed=YES;
                            [appdel.secondViewCtr.navigationController pushViewController:detailVC animated:YES];
                            appdel.secondViewCtr.hidesBottomBarWhenPushed=NO;
                            
                            if (IOS9_OR_LATER) {
                                if(!_isSecondVCTobool){
                                    [self.navigationController popViewControllerAnimated:YES];
                                }
                            }
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)addBaoxiuAlert{
//    __weak QLMAddBaoxiuVC *weakself = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定提交报修订单？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self commitClick];
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                         }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - QLMAddBaoxiuBotCellDelegate
- (void)addHisAddressAction{
//    __weak QLMAddBaoxiuVC *weakself=self;
    QLMEditLocationVC *editLocationVC=[QLMEditLocationVC new];
    editLocationVC.block = ^(NSString *repairAddress, NSString *repairLatitude, NSString *repairLongitude) {
        [self.addressDic setObject:repairAddress forKey:@"repairAddress"];
        [self.addressDic setObject:repairLatitude forKey:@"repairLatitude"];
        [self.addressDic setObject:repairLongitude forKey:@"repairLongitude"];
        bottomcell.addresDetailTF.text=repairAddress;
    };
    editLocationVC.isCannotEdit=YES;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:editLocationVC animated:YES];
}

- (void)addAddressBookAction{
    if(IOS9_OR_LATER){
        __block BOOL authorization=NO;
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        if (status == CNAuthorizationStatusAuthorized){
            authorization = YES;
        }else{
            CNContactStore *contactStore = [[CNContactStore alloc] init];
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    // 成功
                    authorization = YES;
                    [self _presentToContactVC];
                } else {
                    // 失败
                    authorization = NO;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        ETToastWithDelay(@"此应用程序尚未获得访问“通讯录”的权限,请去系统设置中打开此应用的“通讯录”的权限",2);
                    });
                }
            }];
        }
        if (authorization) {
            [self _presentToContactVC];
        }
    }else{
        // 创建联系人选择控制器
        ABPeoplePickerNavigationController *pvc = [[ABPeoplePickerNavigationController alloc] init];
        pvc.peoplePickerDelegate = self;
        if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined){
            ABAddressBookRef bookRef = ABAddressBookCreate();
            ABAddressBookRequestAccessWithCompletion(bookRef, ^(bool granted, CFErrorRef error) {
                if (granted){
                    NSLog(@"授权成功!");
                    [self presentViewController:pvc animated:YES completion:nil];
                }else{
                    NSLog(@"授权失败!");
                }
            });
        }else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
            [self presentViewController:pvc animated:YES completion:nil];
        }
    }
}

// 选择某个联系人时调用
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    
    NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSString *nickname= [NSString stringWithFormat:@"%@%@",lastName,firstName];
    
    NSString *phoneNumber=nil;
    ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex count = ABMultiValueGetCount(multi);
    if (count!=0) {
        NSString *phone =(__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(multi,0);
        phoneNumber=phone;
    }
    
    NSString *attrStr=[[NSString alloc] initWithString:phoneNumber];
    NSString *attrStr1=[attrStr  stringByReplacingOccurrencesOfString:@"(" withString:@""];
    NSString *attrStr2=[attrStr1 stringByReplacingOccurrencesOfString:@")" withString:@""];
    NSString *attrStr3=[attrStr2 stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *attrStr4=[attrStr3 stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    bottomcell.phoneNumTextField.text=[attrStr4 stringByReplacingOccurrencesOfString:@"-" withString:@""];
    bottomcell.truthNameTextField.text=[NSString stringWithFormat:@"%@",nickname];
}

- (void)_presentToContactVC{
    CNContactPickerViewController *contactController = [[CNContactPickerViewController alloc] init];
    contactController.delegate = self;
    contactController.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
    [self presentViewController:contactController animated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 30;
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section==0) {
        
        UIView *footerview=[[UIView alloc] init];
        footerview.backgroundColor=[UIColor whiteColor];
        
        UILabel *_titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, kScreen_width-20, 20)];
        _titleLabel.backgroundColor = [UIColor whiteColor];
        _titleLabel.font = [UIFont systemFontOfSize:15.0f];
        _titleLabel.textColor = [UIColor redColor];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        
        NSString *telStr=@"带*号的地方属于必填项";
        NSMutableAttributedString *aString=[[NSMutableAttributedString alloc] initWithString:telStr];
        [aString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1, 1)];
        _titleLabel.attributedText=aString;
        
        [footerview addSubview:_titleLabel];
        
        return footerview;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if ([classificationId isEqualToString:@"4"]) {
            return 200;
        }
        return 200+50;
    }else if (indexPath.section==1){
        return 150;
    }
    return 130;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        
        if (_isBaoyangDevicebool) {
            topBaoyangcell=[QLMBaoyangDeviceTabCell cellWithTableView:tableView];
            topBaoyangcell.trodecriptionTextView.delegate=self;
            topBaoyangcell.delegate=self;
            [topBaoyangcell _creatMainUI];
            topBaoyangcell.selectionStyle=UITableViewCellSelectionStyleNone;
            return topBaoyangcell;
        }
        
        topcell=[QLMAddBaoxiuTopCell cellWithTableView:tableView];
        [topcell _creatMainUI];
        
        topcell.delegate=self;
        topcell.trodecriptionTextView.delegate=self;
        topcell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        [_btnArray addObject:topcell.firstBtn];
        [_btnArray addObject:topcell.secondBtn];
        [_btnArray addObject:topcell.thirdBtn];
        [_btnArray addObject:topcell.fourthBtn];
        
        return topcell;
        
    }else if (indexPath.section==1){
        bottomcell=[QLMAddBaoxiuBotCell cellWithTableView:tableView];
        bottomcell.delegate=self;
        bottomcell.userInteractionEnabled=YES;
        bottomcell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        bottomcell.truthNameTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserName];
        bottomcell.phoneNumTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginPhoneName];
        
            [bottomcell.phoneNumTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        NSString *addStr=[[NSUserDefaults standardUserDefaults] objectForKey:kDefaultAddress];
        if (![self isNull:addStr]) {
            NSString *detailAddrStr=[[NSUserDefaults standardUserDefaults] objectForKey:@"detailAddr"];
            if ([self isNull:detailAddrStr]) {
                bottomcell.addresDetailTF.text =detailAddrStr;
            }
        }else{
            bottomcell.addresDetailTF.text = addStr;
        }
        
        bottomcell.addresDetailTF.userInteractionEnabled=YES;
        UITapGestureRecognizer *tap1=[[UITapGestureRecognizer alloc] init];
        [tap1 addTarget:self action:@selector(addHisAddressAction)];
        [bottomcell.addresDetailTF addGestureRecognizer:tap1];
        
        return bottomcell;
    }
    
    photocell=[QLMPhotoInfoTabCell cellWithTableView:tableView];
    photocell.delegate=self;
    photocell.isCanEditable=YES;
    photocell.backgroundColor=[UIColor whiteColor];
    photocell.selectionStyle=UITableViewCellSelectionStyleNone;
    return photocell;
}

#pragma mark - UITextField delegate
- (void)tapImageViewAction:(UITapGestureRecognizer *)tapGesture{
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

- (void)textFieldDidChange:(UITextField *)textField{
    if (textField == bottomcell.phoneNumTextField) {
        if (textField.text.length > 11) {
            UITextRange *markedRange = [textField markedTextRange];
            if (markedRange) {
                return;
            }
            NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:11];
            textField.text = [textField.text substringToIndex:range.location];
        }
    }
}

#pragma mark - UITextView delegate
//正在改变
- (void)textViewDidChange:(UITextView *)textView{
    //字数限制操作
    if (textView.text.length >= 200) {
        textView.text = [textView.text substringToIndex:200];
    }
    
    if (_isBaoyangDevicebool) {
        [self changeTextviewState:topBaoyangcell.trodecriptionTextView message:@"请详细描述保养说明（1-50字）"];
    }else{
        [self changeTextviewState:topcell.trodecriptionTextView message:@"请详细描述故障情况（1-50字）"];
    }
}

- (void)changeTextviewState:(QLMPlaceholderTextView *)textView message:(NSString *)message{
    if (!textView.hasText) {
        textView.placeholder = message;
        textView.placeholderColor=[UIColor lightGrayColor];
    }else{
        textView.placeholder = @"";
    }
}

#pragma mark - CNContactPickerViewController delegate
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty{
    
    QLMAddressBookModel *addressBookModel=[[QLMAddressBookModel alloc] init];
    addressBookModel.givenName=contactProperty.contact.givenName;
    addressBookModel.middleName=contactProperty.contact.middleName;
    addressBookModel.familyName=contactProperty.contact.familyName;
    addressBookModel.organizationName=contactProperty.contact.organizationName;
    addressBookModel.phoneNumbers=contactProperty.contact.phoneNumbers;
    
    if (addressBookModel.phoneNumbers.count==0) {
        return;
    }
    CNLabeledValue *labeledValue=(CNLabeledValue *)addressBookModel.phoneNumbers[0];
    CNPhoneNumber *phoneValue = labeledValue.value;
    NSString *phoneNumber = phoneValue.stringValue;
    
    NSString *attrStr=[[NSString alloc] initWithString:phoneNumber];
    NSString *attrStr1=[attrStr  stringByReplacingOccurrencesOfString:@"(" withString:@""];
    NSString *attrStr2=[attrStr1 stringByReplacingOccurrencesOfString:@")" withString:@""];
    NSString *attrStr3=[attrStr2 stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *attrStr4=[attrStr3 stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    bottomcell.phoneNumTextField.text=[attrStr4 stringByReplacingOccurrencesOfString:@"-" withString:@""];
    bottomcell.truthNameTextField.text=[NSString stringWithFormat:@"%@%@%@",addressBookModel.givenName,addressBookModel.middleName,addressBookModel.familyName];
}

#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(buttonIndex == 0){
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        picker.showsNumberOfAssets = YES;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:NULL];
    }else if(buttonIndex == 1){
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        // picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }else if(buttonIndex == 2){
        return;
    }
}

#pragma mark - UIImagepicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [_selectedPhotos addObject:image];
        photocell.selectedPhotos=_selectedPhotos;
        [self uploadImageData:_selectedPhotos];
    }];
}

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray<PHAsset*> *)assets{
    /** 关闭图片选择控制器*/
    [picker dismissViewControllerAnimated:YES completion:^{
        CGFloat scale = [UIScreen mainScreen].scale;
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.resizeMode = PHImageRequestOptionsResizeModeExact;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        
        NSMutableArray *tmpImgArray=[NSMutableArray array];
        /** 遍历选择的所有图片*/
        for (NSInteger i = 0; i < assets.count; i++) {
            PHAsset *asset = assets[i];
            CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);

            /** 获取图片*/
            [[PHImageManager defaultManager] requestImageForAsset:asset
                                                       targetSize:size
                                                      contentMode:PHImageContentModeDefault
                                                          options:options
                                                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                        [tmpImgArray addObject:result];
                                                        if (tmpImgArray.count==assets.count) {
                                                            [_selectedPhotos addObjectsFromArray:tmpImgArray];
                                                            photocell.selectedPhotos=_selectedPhotos;
                                                            [self uploadImageData:_selectedPhotos];
                                                        }

                                                    }];
        }
    }];
}

- (void)uploadImageData:(NSMutableArray *)userHeaderImageArray{
    
    [_selectUrlArr removeAllObjects];
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSMutableDictionary *tokenDic=[NSMutableDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    if ([token length]==0) {
        return;
    }
    ETToast(@"正在上传图片");
    [self.view makeToastActivity:CSToastPositionCenter];
    NSString *urlString=[NSString stringWithFormat:@"%@%@",kBaseURL,@"/rest/appUpload"];
    [ClientTool postUrlPath:urlString withParamers:tokenDic type:userHeaderImageArray success:^(id responseObject) {
        [self.view hideToastActivity];
        NSInteger status = [[responseObject objectForKey:@"flag"] integerValue];
        if (status == 1){
            ETToast([responseObject objectForKey:@"msg"]);
            _selectUrlArr=[NSMutableArray arrayWithArray:responseObject[@"list"]];
        }else{
            ETToast([responseObject objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        [self.view hideToastActivity];
        ETToast(@"服务器连接失败");
    }];
}

/** 相片的最大选择数方法*/
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset {
    NSInteger max = 5;
    if (picker.selectedAssets.count+_selectedPhotos.count+1 > max) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"最多可选择5张照片" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [picker presentViewController:alert animated:YES completion:nil];
        return NO;
    }
    return YES;
}

#pragma mark - QLMPhotoInfoTabCellDelegate
- (void)deleteImageVAction:(NSInteger)itemTag{
    [_selectUrlArr removeObjectAtIndex:itemTag];
}

- (void)selPhotoImageBtnAction{
    UIActionSheet *cameraSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    cameraSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
    [cameraSheet showInView:self.view];
}

- (BOOL)isAssetCanSelect:(id)asset {
    return NO;
}

- (void)tapPreViewerAction:(NSInteger)itemTag{//预览照片
    [XLPhotoBrowser showPhotoBrowserWithImages:_selectedPhotos currentImageIndex:itemTag];
}

#pragma mark - 判断字符串中是否包含表情
- (BOOL)stringContainsEmoji:(NSString *)string{
    NSUInteger len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    if (len < 3) { // 大于2个字符需要验证Emoji(有些Emoji仅三个字符)
        return NO;
    }
    // 仅考虑字节长度为3的字符,大于此范围的全部做Emoji处理
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    Byte *bts = (Byte *)[data bytes];
    Byte bt;
    short v;
    for (NSUInteger i = 0; i < len; i++) {
        bt = bts[i];
        if ((bt | 0x7F) == 0x7F) { // 0xxxxxxx ASIIC编码
            continue;
        }
        if ((bt | 0x1F) == 0xDF) { // 110xxxxx 两个字节的字符
            i += 1;
            continue;
        }
        if ((bt | 0x0F) == 0xEF) { // 1110xxxx 三个字节的字符(重点过滤项目)
            // 计算Unicode下标
            v = bt & 0x0F;
            v = v << 6;
            v |= bts[i + 1] & 0x3F;
            v = v << 6;
            v |= bts[i + 2] & 0x3F;
            
            // NSLog(@"%02X%02X", (Byte)(v >> 8), (Byte)(v & 0xFF));
            
            if ([self emojiInSoftBankUnicode:v] || [self emojiInUnicode:v]) {
                return YES;
            }
            
            i += 2;
            continue;
        }
        if ((bt | 0x3F) == 0xBF) { // 10xxxxxx 10开头,为数据字节,直接过滤
            continue;
        }
        
        return YES; // 不是以上情况的字符全部超过三个字节,做Emoji处理
    }
    return NO;
}

- (BOOL)emojiInSoftBankUnicode:(short)code{
    return ((code >> 8) >= 0xE0 && (code >> 8) <= 0xE5 && (Byte)(code & 0xFF) < 0x60);
}

- (BOOL)emojiInUnicode:(short)code{
    if (code == 0x0023
        || code == 0x002A
        || (code >= 0x0030 && code <= 0x0039)
        || code == 0x00A9
        || code == 0x00AE
        || code == 0x203C
        || code == 0x2049
        || code == 0x2122
        || code == 0x2139
        || (code >= 0x2194 && code <= 0x2199)
        || code == 0x21A9 || code == 0x21AA
        || code == 0x231A || code == 0x231B
        || code == 0x2328
        || code == 0x23CF
        || (code >= 0x23E9 && code <= 0x23F3)
        || (code >= 0x23F8 && code <= 0x23FA)
        || code == 0x24C2
        || code == 0x25AA || code == 0x25AB
        || code == 0x25B6
        || code == 0x25C0
        || (code >= 0x25FB && code <= 0x25FE)
        || (code >= 0x2600 && code <= 0x2604)
        || code == 0x260E
        || code == 0x2611
        || code == 0x2614 || code == 0x2615
        || code == 0x2618
        || code == 0x261D
        || code == 0x2620
        || code == 0x2622 || code == 0x2623
        || code == 0x2626
        || code == 0x262A
        || code == 0x262E || code == 0x262F
        || (code >= 0x2638 && code <= 0x263A)
        || (code >= 0x2648 && code <= 0x2653)
        || code == 0x2660
        || code == 0x2663
        || code == 0x2665 || code == 0x2666
        || code == 0x2668
        || code == 0x267B
        || code == 0x267F
        || (code >= 0x2692 && code <= 0x2694)
        || code == 0x2696 || code == 0x2697
        || code == 0x2699
        || code == 0x269B || code == 0x269C
        || code == 0x26A0 || code == 0x26A1
        || code == 0x26AA || code == 0x26AB
        || code == 0x26B0 || code == 0x26B1
        || code == 0x26BD || code == 0x26BE
        || code == 0x26C4 || code == 0x26C5
        || code == 0x26C8
        || code == 0x26CE
        || code == 0x26CF
        || code == 0x26D1
        || code == 0x26D3 || code == 0x26D4
        || code == 0x26E9 || code == 0x26EA
        || (code >= 0x26F0 && code <= 0x26F5)
        || (code >= 0x26F7 && code <= 0x26FA)
        || code == 0x26FD
        || code == 0x2702
        || code == 0x2705
        || (code >= 0x2708 && code <= 0x270D)
        || code == 0x270F
        || code == 0x2712
        || code == 0x2714
        || code == 0x2716
        || code == 0x271D
        || code == 0x2721
        || code == 0x2728
        || code == 0x2733 || code == 0x2734
        || code == 0x2744
        || code == 0x2747
        || code == 0x274C
        || code == 0x274E
        || (code >= 0x2753 && code <= 0x2755)
        || code == 0x2757
        || code == 0x2763 || code == 0x2764
        || (code >= 0x2795 && code <= 0x2797)
        || code == 0x27A1
        || code == 0x27B0
        || code == 0x27BF
        || code == 0x2934 || code == 0x2935
        || (code >= 0x2B05 && code <= 0x2B07)
        || code == 0x2B1B || code == 0x2B1C
        || code == 0x2B50
        || code == 0x2B55
        || code == 0x3030
        || code == 0x303D
        || code == 0x3297
        || code == 0x3299
        // 第二段
        || code == 0x23F0) {
        return YES;
    }
    return NO;
}

@end
